#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "contactlistview.h"
#include "loginwidget.h"
#include "xmppmanager.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QSystemTrayIcon>
#include <QMacNativeWidget>


#define MAIN_WINDOW_HEIGHT 225
LoginWindow::LoginWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::LoginWindow),
    trayIcon(*new QSystemTrayIcon(this))
{
    ui->setupUi(this);
    contactList = qFindChild<ContactListView*>(this, "ContactList");
    loginWidget = qFindChild<LoginWidget*>(this, "login_widget");
    setFixedSize(280, MAIN_WINDOW_HEIGHT);
    XmppManager::instance().addLoginEventHandler(this);

    QCoreApplication::setOrganizationName("augiekim");
    QCoreApplication::setApplicationName("QtJam");

    //setUnifiedTitleAndToolBarOnMac(true);
    setAttribute(Qt::WA_MacBrushedMetal, true);
    //centralWidget()->move(0,30);
    statusBar()->setSizeGripEnabled(false);

    minimizeAction = new QAction(tr("Mi&nimize"), this);
     connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));

     maximizeAction = new QAction(tr("Ma&ximize"), this);
     connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));

     restoreAction = new QAction(tr("&Restore"), this);
     connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));

     quitAction = new QAction(tr("&Quit"), this);
     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

  QMenu* trayIconMenu = new QMenu(this);
  trayIconMenu->addAction(minimizeAction);
  trayIconMenu->addAction(maximizeAction);
  trayIconMenu->addAction(restoreAction);
  trayIconMenu->addSeparator();
  trayIconMenu->addAction(quitAction);

  trayIcon.setContextMenu(trayIconMenu);
  trayIcon.setToolTip("QtJam");
#if defined (Q_WS_MACX)
  QIcon icon("CoJam2.icns");
#elif defined (Q_WS_WIN)
  QIcon icon("CoJam2.ico");
#endif
  trayIcon.setIcon(icon);
  connect(&trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
  connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
               this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
       trayIcon.show();

   }

LoginWindow::~LoginWindow()
{
    XmppManager::instance().removeLoginEventHandler(this);
    delete ui;
    delete &trayIcon;
}

CUSTOM_EVENT_MAP(LoginWindow) {
    CUSTOM_EVENT(EVENT_LOGIN, onLogin)
    CUSTOM_EVENT_WITH_PARAM(EVENT_LOGOFF, onLogoff, LogoffEvent, errorCode)
}

void LoginWindow::setVisible(bool visible)
 {
     minimizeAction->setEnabled(visible);
     maximizeAction->setEnabled(!isMaximized());
     restoreAction->setEnabled(isMaximized() || !visible);
     QWidget::setVisible(visible);
 }

void LoginWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
 {
     switch (reason) {
     //case QSystemTrayIcon::Trigger:
     case QSystemTrayIcon::DoubleClick:
         //showMessage();
         activateWindow();
         break;
     case QSystemTrayIcon::MiddleClick:
         QMessageBox::question(this, "HELLO", "HELLO", QMessageBox::No, QMessageBox::Yes);
         break;
     default:
         ;
     }
 }
void LoginWindow::messageClicked()
 {
     QMessageBox::information(0, tr("Systray"),
                              tr("Sorry, I already gave what help I could.\n"
                                 "Maybe you should try asking a human?"));
 }

void LoginWindow::showMessage()
 {
     QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information);
     trayIcon.showMessage("WOW", "WWOW", icon,
                           3 * 1000);
 }

void LoginWindow::onLogin()
{
    statusBar()->setSizeGripEnabled(true);
    centralWidget()->layout()->setMargin(0);
    centralWidget()->layout()->removeWidget(loginWidget);
    centralWidget()->layout()->addWidget(contactList);

    setMinimumSize(0,0);
    setMaximumSize(32768,32768);
    if (QSystemTrayIcon::supportsMessages ())
    {
        trayIcon.showMessage("QtJam", "QtJam has just signed in");
    }
}

void LoginWindow::onLogoff(int errorCode)
{
    switch(errorCode)
    {
    case 8:
        QMessageBox::warning(this, tr("Connection lost"),
            tr("An XML parse error occurred. (%1)").arg(errorCode));
        break;
    case 0:
    case 17:
        break;
    default:
        QMessageBox::warning(this, tr("Connection lost"),
          tr("Connection colosed with network error (%1).").arg(errorCode));
    }

    statusBar()->setSizeGripEnabled(false);

    centralWidget()->layout()->removeWidget(contactList);
    centralWidget()->layout()->addWidget(loginWidget);
    setFixedSize(280, MAIN_WINDOW_HEIGHT);
    if (QSystemTrayIcon::supportsMessages ())
    {
        trayIcon.showMessage("QtJam", "QtJam has just signed off");
    }
}

void LoginWindow::logoffClicked()
{
    XmppManager::instance().logout();

}

void LoginWindow::closeEvent(QCloseEvent *event)
 {
    int nRet = QMessageBox::question(this, "Application Exit Question", "Do you want to close QtJam?", QMessageBox::No, QMessageBox::Yes);
    if (nRet == QMessageBox::No)
    {
        event->ignore();
        return;
    }
    XmppManager::instance().logout();
    event->accept();
    std::clog << "Application termination accepted..." << std::endl;
 }
